<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body onload="getUser()">
  <!-- <input type="text" id="uname"><br> -->
  <!-- <button onclick="getUser()"></button> -->
  <input type="text" id="uname"><br>
  <input type="text" id="email"><br>
  <input type="text" id="phone"><br>
  <input type="text" id="user_name"><br>
  <input type="radio" id="man" name="gender" value="1">男
  <input type="radio" id="wom" name="gender" value="0">女
  <input type="radio" id="unk" name="gender" value="-1">保密
  <button onclick="update()">修改</button>
  <script>
    function getUser() {
      var obj = new URLSearchParams(location.search);
      var $uid = obj.get("uid");
      // 1.创建异步对象
      var xhr = new XMLHttpRequest();
      // 4.创建监听，接收相应
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          var r = xhr.responseText;
          if (r == 0) {
            alert("查无此人");
          } else {
            var arr = JSON.parse(r);
            uname.value = arr[0].uname;
            email.value = arr[0].email;
            phone.value = arr[0].phone;
            user_name.value = arr[0].user_name;
            if (arr[0].gender == 1) {
              man.checked = true;
            } else if (arr[0].gender == 0) {
              wom.checked = true;
            } else {
              unk.checked = true;
            }
          }
        }
      }
      // 2.打开连接，创建请求
      xhr.open("get", "/pro/v1/search/" + $uid, true);
      // 3.发送请求
      xhr.send();
    }
    function update() {
      var obj = new URLSearchParams(location.search);
      var $uid = obj.get("uid");
      var $uname = uname.value;
      var $email = email.value;
      var $phone = phone.value;
      var $user_name = user_name.value;
      var $gender = "-1";
      if (man.checked) {
        $gender = man.value;
      } else if (wom.checked) {
        $gender = wom.value;
      } else {
        $gender = unk.value;
      }
      // 1.创建异步对象
      var xhr = new XMLHttpRequest();
      // 4.创建监听，接收响应
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          var r = xhr.responseText;
          if (r == 1) {
            alert("修改成功");
            location.href = "list.html";
          } else {
            alert("修改失败");
          }
        }
      }
      // 2.打开连接，创建请求
      xhr.open("put", "/pro/v1/update", true);
      // 3.发送请求
      xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      var formdata = `uid=${$uid}&uname=${$uname}&email=${$email}&phone=${$phone}&user_name=${$user_name}&gender=${$gender}`;
      xhr.send(formdata);
    }
  </script>
</body>

</html>